package com.sunseen.capacitormachine.modules.parameter.productparameter.modify;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.databinding.FragmentModifyParameterBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.parameter.bean.ProcessBean;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.ModifyParameterEvent;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.ModifySameIVEvent;
import com.sunseen.capacitormachine.modules.parameter.productparameter.ProcessQueryEnd;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.WeakHashMap;

import me.yokeyword.fragmentation.ISupportFragment;

public class ModifyFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_modify_parameter;
    }

    private String batchId;

    private final String status = "status";

    private WeakHashMap<String, Object> flowCardParameterMap = new WeakHashMap<>();
    private WeakHashMap<String, Object> processParameterMap = new WeakHashMap<>();

    private ISupportFragment[] fragments = null;

    private int curFragmentPos = 0;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        Bundle argumentBundle = getArguments();
        if (argumentBundle != null) {
            batchId = argumentBundle.getString("batchId");
        }
        final ModifyProductFlowFragment fragment1 = new ModifyProductFlowFragment();
        if (batchId != null) {
            Bundle bundle = new Bundle();
            bundle.putString("batchId", batchId);
            fragment1.setArguments(bundle);
        }
        final ModifySortingParameterFragment fragment2 = new ModifySortingParameterFragment();
        final ModifyPowerSupplyFragment fragment3 = new ModifyPowerSupplyFragment();
        final ModifySprayCodeFragment fragment4 = new ModifySprayCodeFragment();
        final ModifyAgingParameterFragment fragment5 = new ModifyAgingParameterFragment();
        queryEndListeners = new ProcessQueryEnd[]{fragment2, fragment3, fragment4, fragment5};
        fragments = new ISupportFragment[]{fragment1, fragment2, fragment3, fragment4, fragment5};

        FragmentModifyParameterBinding binding = (FragmentModifyParameterBinding) viewDataBinding;
        binding.toolBar.setNavigationOnClickListener((view) -> hideKeyBoardPop());
        binding.rgFormMenu.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
            switch (checkedId) {
                case R.id.rb_product_flow: {
                    showHideFragment(fragments[0], fragments[curFragmentPos]);
                    curFragmentPos = 0;
                }
                break;
                case R.id.rb_sorting_parameter: {
                    showHideFragment(fragments[1], fragments[curFragmentPos]);
                    curFragmentPos = 1;
                }
                break;
                case R.id.rb_power_supply: {
                    showHideFragment(fragments[2], fragments[curFragmentPos]);
                    curFragmentPos = 2;
                }
                break;
                case R.id.rb_spray_code: {
                    showHideFragment(fragments[3], fragments[curFragmentPos]);
                    curFragmentPos = 3;
                }
                break;
                case R.id.rb_aging_process: {
                    showHideFragment(fragments[4], fragments[curFragmentPos]);
                    curFragmentPos = 4;
                }
                break;
                default:
                    Log.e("test", "rgFormMenu checkedId default");
                    break;
            }
        });
        binding.saveParameterBtn.setOnClickListener((View v) -> {
            final boolean flowCardEmpty = flowCardParameterMap.isEmpty();
            final boolean processEmpty = processParameterMap.isEmpty();
            if (flowCardEmpty && processEmpty) {
                Toast.makeText(getContext(), R.string.parameter_no_modify_tip, Toast.LENGTH_SHORT).show();
            } else {
                if (!flowCardEmpty) {
                    goalSaveCount++;
                }
                if (!processEmpty) {
                    goalSaveCount++;
                }
                if (!flowCardEmpty) {
                    saveFlowCardParameter();
                }
                if (!processEmpty) {
                    saveProcessParameter();
                }
            }
        });
        loadMultipleRootFragment(R.id.fragment_container, 0, fragments);

        EventBus.getDefault().register(this);
        if (batchId != null) {
            queryProcessParameter();
        }
    }

    private ProcessQueryEnd[] queryEndListeners;

    private void queryProcessParameter() {
        RestClient.builder()
                .url(HttpUtil.Process + "/" + batchId)
                .params("deviceNo", DataUtil.DeviceNo)
                .success((String response) -> {
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null) {
                        int status = rootObj.getIntValue("status");
                        if (status == 1) {
                            JSONObject dataObj = rootObj.getJSONObject("data");
                            if (dataObj != null) {
                                ProcessBean bean = JSON.parseObject(
                                        dataObj.getJSONObject("item").toJSONString(),
                                        ProcessBean.class);
                                if (bean != null) {
                                    for (ProcessQueryEnd queryEnd : queryEndListeners) {
                                        queryEnd.onProcessQueryEnd(bean);
                                    }
                                } else {
                                    Toast.makeText(_mActivity, "工艺参数查询结果为空", Toast.LENGTH_SHORT).show();
                                    Log.e("test", "工艺参数查询结果为空");
                                }
                            } else {
                                Toast.makeText(_mActivity, "工艺参数查询结果为空", Toast.LENGTH_SHORT).show();
                                Log.e("test", "工艺参数查询结果为空:");
                            }
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知原因";
                            }
                            Toast.makeText(_mActivity, "工艺参数查询失败: " + msg, Toast.LENGTH_SHORT).show();
                            Log.e("test", "工艺参数查询失败: " + msg);
                        }
                    } else {
                        Toast.makeText(_mActivity, "工艺参数查询失败", Toast.LENGTH_SHORT).show();
                        Log.e("test", "工艺参数查询失败,根数据为空");
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "工艺参数查询结果失败", Toast.LENGTH_SHORT).show();
                    Log.e("test", "工艺参数查询结果失败");
                })
                .error((int code, String msg) -> {
                    Toast.makeText(_mActivity, "工艺参数查询结果错误", Toast.LENGTH_SHORT).show();
                    Log.e("test", "工艺参数查询结果错误 " + code + " " + msg);
                })
                .build()
                .get();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onModifyParameter(ModifyParameterEvent event) {
        Log.e("test", event.isProcess()+" key = " + event.getKey());
        if (event.isProcess()) {
            processParameterMap.put(event.getKey(), event.getValue());
        } else {
            flowCardParameterMap.put(event.getKey(), event.getValue());
        }
    }

    private int goalSaveCount = 0;
    private int saveCount = 0;
    private int responseCount = 0;

    private void checkSaveCount() {
        if (goalSaveCount == saveCount) {
            hideKeyBoardPop();
        } else {
            if (responseCount == goalSaveCount) {
                responseCount = 0;
                goalSaveCount = 0;
            }
        }
    }

    private void saveFlowCardParameter() {
        if (batchId != null) {
            RestClient.builder()
                    .url(HttpUtil.FlowCard + "/" + batchId)
                    .params(flowCardParameterMap)
                    .success((String response) -> {
                        responseCount++;
                        JSONObject rootObj = JSON.parseObject(response);
                        if (rootObj.getIntValue(status) == 1) {
                            Toast.makeText(_mActivity, "流转单保存修改成功", Toast.LENGTH_SHORT).show();
                            saveCount++;
                            checkSaveCount();
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知错误信息";
                            }
                            Toast.makeText(_mActivity, "流转单保存修改失败: " + msg, Toast.LENGTH_SHORT).show();
                        }
                    })
                    .failure(() -> {
                        responseCount++;
                        Log.e("test", "流转单保存修改失败");
                        Toast.makeText(_mActivity, "流转单保存修改失败", Toast.LENGTH_SHORT).show();
                    })
                    .error((int code, String msg) -> {
                        responseCount++;
                        Log.e("test", "流转单保存修改错误: " + code + " " + msg);
                        Toast.makeText(_mActivity, "流转单保存修改错误: " + msg, Toast.LENGTH_SHORT).show();
                    })
                    .build()
                    .patch();
        }
    }

    private void saveProcessParameter() {
        if (batchId != null) {
            RestClient.builder()
                    .url(HttpUtil.Process + "/" + batchId)
                    .params(processParameterMap)
                    .success((String response) -> {
                        responseCount++;
                        JSONObject rootObj = JSON.parseObject(response);
                        if (rootObj.getIntValue(status) == 1) {
                            Toast.makeText(_mActivity, "工艺参数保存修改成功", Toast.LENGTH_SHORT).show();
                            saveCount++;
                            checkSaveCount();
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知错误信息";
                            }
                            Toast.makeText(_mActivity, "工艺参数保存修改失败: " + msg, Toast.LENGTH_SHORT).show();
                        }
                    })
                    .failure(() -> {
                        responseCount++;
                        Log.e("test", "工艺参数保存修改失败");
                        Toast.makeText(_mActivity, "工艺参数保存修改失败", Toast.LENGTH_SHORT).show();
                    })
                    .error((int code, String msg) -> {
                        responseCount++;
                        Log.e("test", "工艺参数保存修改错误: " + code + " " + msg);
                        Toast.makeText(_mActivity, "工艺参数保存修改错误: " + msg, Toast.LENGTH_SHORT).show();
                    })
                    .build()
                    .patch();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onModifySameIv(ModifySameIVEvent event) {
        if (event.isSameI()) {
            processParameterMap.put("I1", event.getValue());
            processParameterMap.put("I2", event.getValue());
            processParameterMap.put("I3", event.getValue());
            processParameterMap.put("I4", event.getValue());
            processParameterMap.put("I5", event.getValue());
            processParameterMap.put("I6", event.getValue());
            processParameterMap.put("I7", event.getValue());
            processParameterMap.put("I8", event.getValue());
            processParameterMap.put("I9", event.getValue());
            processParameterMap.put("I10", event.getValue());
            processParameterMap.put("I11", event.getValue());
            processParameterMap.put("I12", event.getValue());
            processParameterMap.put("I13", event.getValue());
            processParameterMap.put("I14", event.getValue());
            processParameterMap.put("I15", event.getValue());
            processParameterMap.put("I16", event.getValue());
            processParameterMap.put("I17", event.getValue());
            processParameterMap.put("I18", event.getValue());
            processParameterMap.put("chargeI", event.getValue());
            processParameterMap.put("surgeI", event.getValue());
            processParameterMap.put("testI", event.getValue());
        } else {
            processParameterMap.put("V1", event.getValue());
            processParameterMap.put("V2", event.getValue());
            processParameterMap.put("V3", event.getValue());
            processParameterMap.put("V4", event.getValue());
            processParameterMap.put("V5", event.getValue());
            processParameterMap.put("V6", event.getValue());
            processParameterMap.put("V7", event.getValue());
            processParameterMap.put("V8", event.getValue());
            processParameterMap.put("V9", event.getValue());
            processParameterMap.put("V10", event.getValue());
            processParameterMap.put("V11", event.getValue());
            processParameterMap.put("V12", event.getValue());
            processParameterMap.put("V13", event.getValue());
            processParameterMap.put("V14", event.getValue());
            processParameterMap.put("V15", event.getValue());
            processParameterMap.put("V16", event.getValue());
            processParameterMap.put("V17", event.getValue());
            processParameterMap.put("V18", event.getValue());
            processParameterMap.put("chargeV", event.getValue());
            processParameterMap.put("surgeV", event.getValue());
            processParameterMap.put("testV", event.getValue());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private void hideKeyBoardPop() {
        hideSoftInput();
        pop();
    }
}
